package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Visit;
import cn.wolfcode.wolf2w.redis.service.IVisitRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Service
public class VisitRedisServiceImpl implements IVisitRedisService{
    @Autowired
    private StringRedisTemplate template;


    @Override
    public void updateView(Visit visit,String userId) {
        //先拼接key
        String todayKey= RedisKeys.VISIT_TODAY.join(visit.getWoId());
        String totalKey=RedisKeys.VISIT_TOTAL.join(visit.getWoId());
        //从Redis库中拿
        String todayView = template.opsForValue().get(todayKey);
        String totalView=template.opsForValue().get(totalKey);
        //对于总访问量,直接+1即可
        if (userId.equals(visit.getWoId())){
            //如果当前窝为自己不做任何操作
            if (todayView==null){todayView="0";}
            visit.setTodayView(Integer.valueOf(todayView));
        }else {
            //对于今日访问量,直接偏移1即可
            template.opsForValue().set(totalKey,visit.getTotalView().toString());
            if (todayKey!=null){
                Long increment = template.opsForValue().increment(todayKey);
                visit.setTodayView(Integer.valueOf(increment.toString()));
            }else {
                //创建新的redis
                long dateBetween = DateUtil.getDateBetween(DateUtil.getEndDate(new Date()), new Date());
                template.opsForValue().set(todayKey, "1", dateBetween, TimeUnit.SECONDS);
                visit.setTodayView(1);
            }
        }

    }

    @Override
    public void setView(Visit visit) {
        //先拼接key
        String todayKey= RedisKeys.VISIT_TODAY.join(visit.getWoId());
        String totalKey=RedisKeys.VISIT_TOTAL.join(visit.getWoId());
        //从Redis库中拿
        String todayView = template.opsForValue().get(todayKey);
        String totalView=template.opsForValue().get(totalKey);
        //设置进visit中
        visit.setTodayView(Integer.valueOf(todayView));
    }
}
